package project02.service;

import javafx.scene.input.DataFormat;
import project02.domain.*;
import project02.view.IndexView;
import project02.view.JobView;
import refelct.Student;
import sun.util.calendar.BaseCalendar;

import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class JobService {
    static {
        File file=new File("src/project02/information/yourWorkInformation.txt");
        if (!file.exists()){
            try {
                file.createNewFile();
                HashSet<UidJid>list=new HashSet<>();
                ObjectOutputStream ois=new ObjectOutputStream(new FileOutputStream("src/project02/information/yourWorkInformation.txt"));
                ois.writeObject(list);
                ois.flush();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    final static String JOB_INFORMATION="src/project02/information/jobInformation.txt";
    Date workStart=new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

    public static void getJobInformation(Integer jid, String companyName, String jobName, String jobTypeName, Integer jobLevel, String jobContent, Integer jobDemand, Integer jobTime,
                                         Integer salary,Integer status) throws IOException, ClassNotFoundException {

    File file=new File(JOB_INFORMATION);
    if(!file.exists()){
        file.createNewFile();
        ArrayList<Job>list=new ArrayList<>();
        ObjectOutputStream ois=new ObjectOutputStream(new FileOutputStream(JOB_INFORMATION));
        ois.writeObject(list);
        ois.flush();
        ois.close();
    }
        ObjectInputStream ins=new ObjectInputStream(new FileInputStream(JOB_INFORMATION));
        ArrayList<Job>js=(ArrayList<Job>)ins.readObject();


        js.add(new Job(jid,companyName,jobName,jobTypeName,jobLevel,jobContent,jobDemand,
                jobTime, salary,status));

        FileOutputStream fos = new FileOutputStream(JOB_INFORMATION);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(js);
        os.flush();

        System.out.println("兼职信息录入完成.");
        fos.close();
        os.close();

    }

    public static void checkWorkAll() throws IOException, ClassNotFoundException {
        ObjectInputStream jis = new ObjectInputStream(new FileInputStream(JOB_INFORMATION));

        ArrayList<Job> list  = (ArrayList<Job>)jis.readObject();

        for (int i = 0; i < list.size(); i++ ){
            Job j = list.get(i);
            System.out.println(j);
        }

       jis.close();

    }

    /**
     *
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void checkWork() throws IOException, ClassNotFoundException {
        ObjectInputStream jis = new ObjectInputStream(new FileInputStream("src/project02/information/yourWorkInformation.txt"));
        HashSet<UidJid> list  = (HashSet<UidJid>)jis.readObject();
        jis.close();
        for (UidJid uidJid : list) {
            if (uidJid.getUid().equals(CurrentUser.currentUser.getUid())){
                ObjectInputStream ins=new ObjectInputStream(new FileInputStream(new File(JOB_INFORMATION)));
                ArrayList<Job>jjs=(ArrayList<Job>)ins.readObject();
                ins.close();
             for (Job jj : jjs) {
                    if (jj.getJid().equals(uidJid.getJid())){
                        System.out.println(jj);
                    }

                }
            }


        }
        System.out.println("以下是您正在完成的工作。"+list);
        jis.close();
    }

    /**
     *
     * @param level
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public static void applyJob(Integer level) throws IOException, ClassNotFoundException {
        
        ObjectInputStream jis = new ObjectInputStream(new FileInputStream(JOB_INFORMATION));

        ArrayList<Job> list  = (ArrayList<Job>)jis.readObject();

        for (int i = 0; i < list.size(); i++ ){
            Job j = list.get(i);

            if (j.getJobLevel()<=level&&j.getJobDemand()!=0){
                System.out.println("以下是符合您条件的兼职工作："+j);
            }else if (j.getJobDemand()==0){
                System.out.println("很遗憾，工作岗位已满。");
            }else{
                System.out.println("十分抱歉，当前没有您能接取的兼职委托，请耐心等待。");

            }
        }

        jis.close();

    }

    public static void applyJobForYourself(Integer id, SimpleDateFormat df, Date workStart) throws IOException, ClassNotFoundException {
//        File file=new File("src/project02/information/yourWorkInformation.txt");
//        if (!file.exists()){
//            file.createNewFile();
//
//        }
        ObjectInputStream jis = new ObjectInputStream(new FileInputStream(JOB_INFORMATION));

        ArrayList<Job> list  = (ArrayList<Job>)jis.readObject();

        for (int i = 0; i < list.size(); i++ ){
            Job j = list.get(i);

            if (j.getJid().equals(id)&&j.getJobDemand()>0){


                System.out.println("目前这个职位需要"+j.getJobDemand()+"人"+"您可以加入工作！");
                j.setJobDemand(j.getJobDemand()-1);
                j.setStatus(1);
                 df = new SimpleDateFormat("yyyy-MM-dd");
                System.out.println("申请成功！于 "+df.format(workStart)+" 开始工作。");


                FileOutputStream fos = new FileOutputStream(JOB_INFORMATION);
                ObjectOutputStream os = new ObjectOutputStream(fos);
                os.writeObject(list);
                os.flush();
                os.close();
                fos.close();
                HashSet<UidJid>youJob=new HashSet<>();
                youJob.add(new UidJid(CurrentUser.currentUser.getUid(),j.getJid()));
                 fos = new FileOutputStream("src/project02/information/yourWorkInformation.txt");
                 os = new ObjectOutputStream(fos);
                os.writeObject(youJob);
                os.flush();
                os.close();
                fos.close();


            }

        }

        jis.close();

    }

    public static void endJob(Integer id1, Date workStart) throws IOException, ClassNotFoundException, ParseException, InterruptedException {

        ObjectInputStream jis = new ObjectInputStream(new FileInputStream("src/project02/information/yourWorkInformation.txt"));
        HashSet<UidJid> list  = (HashSet<UidJid>)jis.readObject();
        ArrayList<Job> jobs = null;
        for (UidJid uj : list) {

            if (uj.getJid().equals(id1)&&uj.getUid().equals(CurrentUser.currentUser.getUid())){

                Scanner sc=new Scanner(System.in);
                System.out.println("请输入结束时间：");
                String end=sc.next();
                DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

                Date dateEnd = format.parse(end);
                Date dateStart = workStart;

                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src/project02/information/jobInformation.txt"));
                jobs = (ArrayList<Job>)ois.readObject();
                Job j = null;
                for (Job job : jobs) {
                    if (Objects.equals(job.getJid(), id1)){
                        j = job;
                        break;
                    }
                }
                if (j == null){
                    throw new RuntimeException("工作查询出错，请联系管理员");
                }

                long day = (dateEnd.getTime()-dateStart.getTime())/(24*60*60*1000);
                Integer day1= Math.toIntExact(day);
                System.out.println("工作总耗时为："+day1+"天");
                j.setStatus(-1);
                if (day1<=j.getJobTime()&&j.getJobLevel()==5){
                    Integer tmp=CurrentUser.currentUser.getBalance();
                    tmp+=j.getSalary();

                    System.out.println("按时完成工作,您的信用等级良好，请继续保持，" +
                            "本次工作共获得： "+j.getSalary());
                }else if (day1<=j.getJobTime()&&j.getJobLevel()<5){
                    Integer tmp=CurrentUser.currentUser.getBalance();
                    tmp+=j.getSalary();
                    System.out.println("按时完成工作,您的信用等级为 "+j.getJobLevel()+" 恢复信用等级还需完成"
                                    +((5-j.getJobLevel())*3-1)+"次工作"+
                            "本次工作共获得： "+j.getSalary());

                }else if (day1>j.getJobTime()&&j.getJobLevel()<=5){
                  j.setJobLevel(j.getJobLevel()-1);
                    Integer tmp=CurrentUser.currentUser.getBalance();
                    Integer salary=j.getSalary()-(j.getSalary()/j.getJobTime()*(day1-j.getJobTime()));
                    if(salary<=0){
                        salary=0;
                    j.setSalary(salary);
                    tmp+=j.getSalary();}

                    System.out.println("逾期完成工作,您的信用等级降为 "+j.getJobLevel()+"  恢复信用等级还需完成"
                            +((5-j.getJobLevel())*3)+"次工作  "+
                            "本次工作共获得："+j.getSalary());
                    if(j.getJobLevel()==0){
                        System.out.println("警告！信用等级为零，无法再接取任何兼职委托！");
                    }
                }



            }else {
                System.out.println("未查询到该工作，输入错误！返回主程序。");
                IndexView.softwareMainMenu();

            }




        jis.close();
        FileOutputStream fos = new FileOutputStream("src/project02/information/jobInformation.txt");
        ObjectOutputStream os = new ObjectOutputStream(fos);

        os.writeObject(jobs);
        fos.close();
        os.close();
        ObjectInputStream ins=new ObjectInputStream(new FileInputStream("src/project02/information/yourWorkInformation.txt"));
        HashSet<UidJid>kk=(HashSet<UidJid>)ins.readObject();
        ins.close();
            for (UidJid uidJid : kk) {
                if (uidJid.getJid().equals(id1)) {
                    kk.remove(uidJid);
                    System.out.println("该工作已移除");
                } else {
                    System.out.println("输入错误！返回主界面！");
                    IndexView.softwareMainMenu();
                }

            }
            ObjectOutputStream ois=new ObjectOutputStream(new FileOutputStream("src/project02/information/yourWorkInformation.txt"));
            ois.writeObject(kk);
            ois.flush();
            ois.close();




    }}


    public static void modifyJobContent(Integer inputUid,Integer inputLevel) throws IOException, ClassNotFoundException, ParseException, InterruptedException {
        ObjectInputStream jis = new ObjectInputStream(new FileInputStream(JOB_INFORMATION));

        ArrayList<Job> list  = (ArrayList<Job>)jis.readObject();
        for (Job job : list) {
            if (job.getJid().equals(inputUid)){
                if(inputLevel<=5){
                job.setJobLevel(inputLevel);}else {
                    System.out.println("兼职等级只有1到5级，输入错误！");
                    IndexView.softwareMainMenu();
                }
                break;
            }

        }
        ObjectOutputStream ois=new ObjectOutputStream(new FileOutputStream(JOB_INFORMATION));
        ois.writeObject(list);
        ois.flush();
        ois.close();
        jis.close();


    }

    public static boolean check(Integer id) throws IOException, ClassNotFoundException {
        ObjectInputStream ins=new ObjectInputStream(new FileInputStream("src/project02/information/yourWorkInformation.txt"));
        HashSet<UidJid>list=(HashSet<UidJid>)ins.readObject();
        ins.close();
        for (UidJid uidJid : list) {
            if (Objects.equals(uidJid.getJid(), id) &&uidJid.getUid().equals(CurrentUser.currentUser.getUid())){
                System.out.println("该工作已申请过了！你是个包子吗？");
                return false;
            }

        }
        return true;

    }
}



    /*FileOutputStream fos = new FileOutputStream("/information/userInformation.txt");
    ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(inf);

        System.out.println("信息录入完成.");
       fos.close();
      os.close();

   /* private ArrayList<Job>pro=new ArrayList<>();
    private int count=1;
    //添加工作描述
    public boolean addJob(char num) {
        switch (num) {
            case '1':
                if (isAdded("文案兼职")) {
                    return false;
                }
               pro.add(new Job(count++,"刮风寨责任有限公司","文案兼职","小时工",3,"文案撰写",3,"4小时",400,false,null));
                break;
            case '2':
                if (isAdded("家教")) {
                    return false;
                }
                pro.add(new Job(count++,"天人教育责任有限公司",
                        "家教","月工",4,"高三理科",1,"一个月",4500,false,null));
                break;
            case '3':
                if (isAdded("餐厅招待")) {
                    return false;
                }
                pro.add(new Job(count++,"三石餐厅","服务员",
                        "小时工",3,"文案撰写",3,"4小时",400,false,null));
                break;
            case '4':
                if (isAdded("图书管理员")) {
                    return false;
                }
                pro.add(new Job(count++,"新华书店","图书管理员",
                        "小时工",3,"管理登记图书出借",6,"12小时",400,false,null));

                break;
        }
        System.out.println("已添加工作：" + pro.get(count - 2).getJobName());
        return true;
    }
    private boolean isAdded(String JobName){
        for (Job p:pro){
            if (p.getJobName().equals(JobName)){
                return true;
            }
        }
        return false;

    }
    */





